import { type Product } from '@/types/product'
import { getNearbyProductListApi } from '@/api/productInfo'
import { useNearbyProductStore } from '@/stores/modules/nearbyProduct'
export default function () {
  // 获取 store 实例
  const nearbyProductStore = useNearbyProductStore()
  // 获取附近商品列表
  const getNearbyProductList = async (reset: boolean = false, adcode: string) => {
    // 如果重置，则重置分页参数和商品列表
    if (reset) {
      nearbyProductStore.currentPage = 1
      nearbyProductStore.productList = []
      nearbyProductStore.hasMore = true
    }
    // 如果没有更多商品，则直接返回
    if (!nearbyProductStore.hasMore) {
      ElMessage.warning('附近没有更多商品了')
      return
    }

    // 调用 API 获取商品列表
    const res = await getNearbyProductListApi(
      nearbyProductStore.currentPage,
      nearbyProductStore.pageSize,
      adcode,
    )
    if (res.code === 0) {
      // 处理商品数据
      const newProducts = res.data.records.map((item: Product) => ({
        ...item,
        // 将图片 URL 字符串转为数组
        image: item.image.split(',').map(url => url.replace(/^'|'$/g, '')),
      }))
      // 更新商品列表
      nearbyProductStore.productList = [...nearbyProductStore.productList, ...newProducts]
      // 如果获取的商品数量少于 pageSize，说明没有更多商品了
      if (newProducts.length < nearbyProductStore.pageSize) {
        nearbyProductStore.hasMore = false
      } else {
        // 否则，页码加1
        nearbyProductStore.currentPage++
      }
    } else if (res.code === 1) {
      ElMessage.warning(res.msg)
      nearbyProductStore.hasMore = false
    }
  }

  return {
    getNearbyProductList,
  }
}
